<?php
set_time_limit(0);

include_once (dirname(__FILE__).'/config/database.php');
include_once (dirname(__FILE__).'/class/Log.inc');
include_once (dirname(__FILE__).'/class/Mysql/Exception.inc');
include_once (dirname(__FILE__).'/class/Mysql.inc');


define('LOCK_FILE', dirname(__FILE__).'/lock/sendPayDaemon.lock');
define('LOG_LEVEL', 'DEBUG');

$LogFile = dirname(__FILE__).'/log/sendPayDaemon'.date('Y.m.d').'.log';

$Log = new Zw_Log();
$Log->setCurrLogLevel(LOG_LEVEL);
$Log->setLogFile($LogFile);

$handle = fopen(LOCK_FILE, 'w+');
if(!flock($handle, LOCK_EX|LOCK_NB)){
	$Log->write('进程已经启动，请不要重复启动');
	exit();
}

$GmDb = new Zw_Mysql();
$GmDb->setLog($Log);
$GmDb->connect($gmDatabaseHost, $gmDatabaseUsername, $gmDatabasePassword, $gmDatabaseName);

while (1) {
	$LogFile = dirname(__FILE__).'/log/sendPayDaemon'.date('Y.m.d').'.log';
	$Log->setLogFile($LogFile);
	
	try {
		$sql = "
			select
				a.`applyId`,
				c.`operatorFlag`,
				b.`domain`,
				a.`account`,
				a.`money`
			from
				`t_data_pay_apply` a
			left join
				`t_data_game_area` b
			on
				a.`gameAreaId` = b.`gameAreaId`
			left join
				`t_data_operator` c
			on
				b.`operatorId` = c.`operatorId`
			where
				a.`status` = 2
			limit 1
		";
		
		$row = $GmDb->getRow($sql);
		
		if($row === false) {
			throw new Exception('', 0);
		}
		
		$applyId = $row['applyId'];
		
		$sql = "
			update
				`t_data_pay_apply`
			set
				`status` = 4
			where
				`applyId` = '{$applyId}'
		";
		
		if( !($GmDb->getAffectedRow() > 0) ) {
			throw new Exception('', 0);
		}
		
		$domain = $row['domain'];
		$operatorFlag = $row['operatorFlag'];
		$username = $row['account'];
		$money = $row['money'];
		$gold = (int)($money / 10);
		$tmp = explode(' ', microtime());
		$orderId = "SEND_VIP_" . $tmp[1] . substr($tmp[0], 2);
		$time = time();
		$sign = 'aaa';
		
		$url = "http://{$domain}/api/{$operatorFlag}/pay.php?username={$username}&orderId={$orderId}&money={$money}&gold={$gold}&time={$time}&sign={$sign}";
		$Log->write($url, 'DEBUG');
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$response = curl_exec($ch);
		
		if($response === '0') {
			$status = 5;
		}
		else {
			$status = 6;
			$Log->write("充值失败，游戏服务器返回：{$response}");
		}
		
		$sql = "
			update
				`t_data_pay_apply`
			set
				`status` = '{$status}'
			where
				`applyId` = '{$applyId}'
		";
		$GmDb->query($sql);
	}
	
	catch(Exception $e) {
		
	}
	
	sleep(30);
}